package com.bw.kylin1705f.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bw.kylin1705f.entity.Role;
import com.bw.kylin1705f.entity.User;
import com.bw.kylin1705f.mapper.UserMapper;
import com.bw.kylin1705f.service.IRoleService;
import com.bw.kylin1705f.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Mht
 * @since 2019-12-05
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, UserDetailsService {


    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    IRoleService roleService;

    @Override
    @Cacheable(value = "userlistcache")
    public List<User> getUserList() {
        Wrapper<User> wrapper = new EntityWrapper<User>();
        List<User> users = this.selectList(wrapper);
        return users;
    }

    @Override
    public List<User> getUserListByParam(User user) {
        return this.baseMapper.getUserList(user);
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.info("用户名：{}",s);
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("username",s);
        User user = this.selectOne(wrapper);
        if (user==null){
            throw  new UsernameNotFoundException("用户名不存在");
        }
        List<Role> roleUserMyUid = roleService.getRoleUserMyUid(user.getId());
        String[] roleName = new String[roleUserMyUid.size()];
        for (int i=0;i<roleUserMyUid.size();i++){
            roleName[i] = roleUserMyUid.get(i).getName();
        }

        return new org.springframework.security.core.userdetails.User(s,user.getPassword(), AuthorityUtils.createAuthorityList(roleName));
    }
}
